package cn.jisol.ngame.listener;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassUtil;
import cn.jisol.ngame.rpc.NGameRPC;
import cn.jisol.ngame.rpc.NGameRPCClass;
import cn.jisol.ngame.rpc.NGameRPCMethod;
import cn.jisol.ngame.util.spring.SpringBeanUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Method;
import java.util.*;

@Component
public class InitNGameRPCListener {

    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationEvent(ContextRefreshedEvent event) {


        System.out.println("--- 初始化 --- NGameRPC ---");

        Set<Class<?>> classes = this.getScanPackage();

        classes.forEach((Class<?> value) -> {
            if(Objects.nonNull(AnnotationUtil.getAnnotation(value, NGameRPCClass.class))){
                for (Method method : value.getMethods()){
                    if (Objects.nonNull(AnnotationUtils.findAnnotation(method, NGameRPCMethod.class)))
                        NGameRPC.addRPCMethod(value,method);
                }
            }
        });

        System.out.println(String.format("扫描到RPC Class数量:%s",NGameRPC.lClassSize()));

    }

    public Set<Class<?>> getScanPackage(){
        return ClassUtil.scanPackage("");
    }
}
